//
//  SelectTagsCellFlowLayout.m
//  PigMarket
//
//  Created by Felix on 2019/3/25.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "SelectTagsCellFlowLayout.h"

@interface SelectTagsCellFlowLayout ()

//@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes*> *itemsAttributes;

/**
 总的布局对象数组，包括item，sectionHeader，footerHeader
 */
@property (nonatomic , strong) NSMutableArray *attributesArray;
/**
 item的布局对象数组
 */
@property (nonatomic , strong) NSMutableArray *itemsAttributes;
/** header的布局对象数组 */
@property (nonatomic , strong) NSMutableArray *headerAttributes;
/** footer的布局对象数组 */
@property (nonatomic , strong) NSMutableArray *footerAttributes;
/** 计算 collectionview 的内容高度 */
@property (nonatomic , assign) CGFloat contentHeight;

/**
 lastAttributes
 */
@property (nonatomic , strong) UICollectionViewLayoutAttributes *lastAttribute;

@end

@implementation SelectTagsCellFlowLayout

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.headerViewHeight = 0.0;
        self.footerViewHeight = 0.0;
        self.itemHeight = 30.0;
        self.lineSpacing = 4;
        self.interitemSpacing = 4;
        self.labelFont = [UIFont systemFontOfSize:12];
        self.itemInset = UIEdgeInsetsZero;
        self.itemViewMaxWidth = SCREEN_WIDTH;
    }
    return self;
}
// 当collectionView布局item时 第一个执行的方法
- (void)prepareLayout {
    [super prepareLayout];
    self.itemViewMaxWidth = SCREEN_WIDTH - self.itemInset.left - self.itemInset.right;
    // 所有内容的布局属性数组
    self.attributesArray = [NSMutableArray array];
    // item的数据模型是：每个元素是一个数组，代表一个section，每个元素的数组里面是每个section的item的Attribute
    self.itemsAttributes = [NSMutableArray array];
    // 记录 collectionview 的内容高度
    self.contentHeight = 0.0;
    // section总数
    NSInteger sectionCount = self.collectionView.numberOfSections;
    for (int sectionNum = 0; sectionNum < sectionCount; sectionNum++) {
        // 每个section的cell数
        NSInteger itemsOfSection = [self.collectionView numberOfItemsInSection:sectionNum];
        for (int i = 0; i < itemsOfSection; i++) {
            // 设置Attributes,最后一个section如果有footer，没有加进去(因为循环的是section，item)
            [self setupItemsAttributesWithIndexPath:[NSIndexPath indexPathForRow:i inSection:sectionNum]];
            // 判断最后一个section是否有footer，有点话，需要加进数组
            if (i == itemsOfSection - 1 && sectionNum == sectionCount - 1) {
                if ([self.delegate respondsToSelector:@selector(collectionViewDynamicFooterSizeWithIndexPath:)]) {
                    [self setupFooterAttributesWithIndexPath:[NSIndexPath indexPathForRow:i inSection:sectionNum]];
                    UICollectionViewLayoutAttributes *footerAttributes = self.footerAttributes.lastObject;
                    self.contentHeight = CGRectGetMaxY(footerAttributes.frame) + self.lineSpacing;
                }
            }
        }
    }
}
/** 设置ItemsAttributes */
- (void)setupItemsAttributesWithIndexPath:(NSIndexPath *)indexPath {
    CGFloat x = 0.0;
    CGFloat y = 0.0;
    CGFloat width = [self getItemWidth:indexPath];
    CGFloat height = self.itemHeight;
    self.lastAttribute = self.attributesArray.lastObject;
    
    if (self.attributesArray.count != 0) {
        if (self.lastAttribute.indexPath.section == indexPath.section) { // 同一个section
            if (CGRectGetMaxX(self.lastAttribute.frame) + self.interitemSpacing + width > self.itemViewMaxWidth) { // item需要换行
                x = self.itemInset.left + self.interitemSpacing;
                y = CGRectGetMaxY(self.lastAttribute.frame) + self.lineSpacing;
            } else { // item不需换行
                x = CGRectGetMaxX(self.lastAttribute.frame) + self.interitemSpacing;
                y = CGRectGetMinY(self.lastAttribute.frame);
            }
        } else { // 不同section
            // 不同section，先增加上一个section的footer,内部会判断是否需要添加
            [self setupFooterAttributesWithIndexPath:indexPath];
            // 添加新的section的item的Attribute集合
            [self.itemsAttributes addObject:[NSMutableArray array]];
            // 添加 header 的布局,内部会判断是否需要添加
            [self setupHeaderAttributesWithIndexPath:indexPath];
            // 设置新的section的第一个item
            x = self.itemInset.left + self.interitemSpacing;
            y = self.lineSpacing + CGRectGetMaxY(self.lastAttribute.frame);
        }
    } else { // 第一个section的item
        // 添加第一个元素：第一个section的item的Attribute集合
        [self.itemsAttributes addObject:[NSMutableArray array]];
        // 添加 header 的布局,内部会判断是否需要添加
        [self setupHeaderAttributesWithIndexPath:indexPath];

        x = self.itemInset.left + self.interitemSpacing;
        y = self.lineSpacing;
        if (self.headerAttributes.count > 0) {
            y = self.lineSpacing + self.lastAttribute.size.height;
        }
    }
    [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attributes.frame = CGRectMake(x, y, width, height);
    self.contentHeight = CGRectGetMaxY(attributes.frame) + self.lineSpacing;
    [self.itemsAttributes[indexPath.section] addObject:attributes];
    [self.attributesArray addObject:attributes];
}
/** 设置HeaderAttributes */
- (void)setupHeaderAttributesWithIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *headerAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:indexPath];
    
    CGFloat y = self.lastAttribute ? CGRectGetMaxY(self.lastAttribute.frame) + self.lineSpacing : 0;
    CGFloat headerWidth = 0.0;
    CGFloat headerHeight = 0.0;
    if ([self.delegate respondsToSelector:@selector(collectionViewDynamicHeaderSizeWithIndexPath:)]) {
        CGSize size = [self.delegate collectionViewDynamicHeaderSizeWithIndexPath:indexPath];
        headerWidth = size.width;
        headerHeight = size.height;
    }
    if (headerHeight > 0) {
        headerAttributes.frame = CGRectMake(0, y, headerWidth, headerHeight);
        [self.headerAttributes addObject:headerAttributes];
        [self.attributesArray addObject:headerAttributes];
        self.lastAttribute = self.attributesArray.lastObject;
    }
}
/** 设置FooterAttributes */
- (void)setupFooterAttributesWithIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *footerAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter withIndexPath:indexPath];
    
    CGFloat y = self.lastAttribute ? CGRectGetMaxY(self.lastAttribute.frame) + self.lineSpacing : 0;
    CGFloat footerWidth = 0.0;
    CGFloat footerHeight = 0.0;
    if ([self.delegate respondsToSelector:@selector(collectionViewDynamicFooterSizeWithIndexPath:)]) {
        CGSize size = [self.delegate collectionViewDynamicFooterSizeWithIndexPath:indexPath];
        footerWidth = size.width;
        footerHeight = size.height;
    }
    if (footerHeight > 0) {
        footerAttributes.frame = CGRectMake(0, y, footerWidth, footerHeight);
        [self.footerAttributes addObject:footerAttributes];
        [self.attributesArray addObject:footerAttributes];
        self.lastAttribute = self.attributesArray.lastObject;
    }
}
/** 计算Item宽度 */
- (CGFloat)getItemWidth:(NSIndexPath *)indexPath {
    NSString *cellContent = [self.delegate collectionViewItemSizeWithIndexPath:indexPath];
    CGSize size = [cellContent sizeWithAttributes:@{NSFontAttributeName:self.labelFont}];
    return size.width + 30 + 2;
//    return MAX(size.width, self.itemHeight);
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attributesArray;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.itemsAttributes[indexPath.section][indexPath.item];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    if ([elementKind isEqual:UICollectionElementKindSectionHeader]) {
        return self.headerAttributes.count > 0 ? self.headerAttributes[indexPath.section] : nil;
    } else {
        return self.footerAttributes[indexPath.section];
    }
}
- (CGSize)collectionViewContentSize {
    return CGSizeMake(self.itemViewMaxWidth, self.contentHeight + self.lineSpacing);
}

#pragma mark - getter and setter
// header 的布局属性数组
- (NSMutableArray *)headerAttributes {
    if ( !_headerAttributes ) {
        _headerAttributes = [NSMutableArray array];
    }
    return _headerAttributes;
}

// footer 的布局属性数组
- (NSMutableArray *)footerAttributes {
    if ( !_footerAttributes ) {
        _footerAttributes = [NSMutableArray array];
    }
    return _footerAttributes;
}

- (UICollectionViewLayoutAttributes *)lastAttribute {
    if (!_lastAttribute) {
        _lastAttribute = [[UICollectionViewLayoutAttributes alloc] init];
    }
    return _lastAttribute;
}

@end
